package com.lge.qcontact.members;


import com.lge.qcontact.R;
import com.lge.qcontact.threads.FindAccountThread;
import com.lge.qcontact.utils.MUtils;

import android.annotation.SuppressLint;

import android.app.TabActivity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class FindAccountActivity extends TabActivity {

	private TextView textResult;
	private TextView textResult2;
	
	private EditText editName;
	private EditText editEmail;
	private EditText editId;
	private EditText editPhone;
	
	private Button btnConfirm;
	private Button btnSend;
	private Button btnCancel;
	private Button btnCancel2;
	private Button btnError;
	private Button btnError2;
	
	private String resultId = null; 	// ID 검색 결과
	private String resultPwd = null;	// Password 검색 결과
	

	/* 검색된 ID 결과 출력하는 핸들러 */
	private Handler mIdHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			Bundle result = msg.getData();
			resultId = result.getString("ID");
			textResult.setVisibility(View.VISIBLE);
			btnError.setVisibility(View.VISIBLE);
			
			MUtils.log("FIND_ACCOUNT", "[Handler]Searched ID:" + resultId);
			if(resultId != null){
				textResult.setText("귀하의 아이디는 " + resultId + " 입니다.");
				btnError.setOnClickListener(new InitEditBox());
			} else {
				textResult.setText("존재하는 아이디가 없습니다.\n다시 시도해주십시오.");
				btnError.setOnClickListener(new InitEditBox());
			}
		}
		
	};
	
	/* 검색된 Password 결과 출력하는 핸들러 */
	private Handler mPwdHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
		
			Bundle result = msg.getData();
			resultPwd = result.getString("PWD");
			textResult2.setVisibility(View.VISIBLE);
			btnError2.setVisibility(View.VISIBLE);
			
			MUtils.log("FIND_ACCOUNT", "[Handler] Searched password:" + resultPwd);
			if(resultPwd != null){
				String phoneNo = editPhone.getText().toString();
				String message = "[Q contact] 귀하의 패스워드는  " + resultPwd + "  입니다.";
				
				if (phoneNo.length()>0){    
			        try {
						sendSMS(phoneNo, message);
						MUtils.log("FIND_ACCOUNT", "   Success sending sms...");
						MUtils.toast(FindAccountActivity.this, "SMS 발신 성공");
					
			        } catch (Exception e) {

			        	MUtils.log("FIND_ACCOUNT", "   Fail sending sms...");
						MUtils.toast(FindAccountActivity.this, "SMS 발신 실패");
						MUtils.log("SMSTest",e.getMessage());
					}
				}else{
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
				}
				textResult2.setText("해당 번호로 비밀번호를 전송하였습니다. ");
				btnError2.setOnClickListener(new InitEditBox());
				
			} else {
				textResult2.setText("존재하는 아이디가 없습니다.\n다시 시도해주십시오.");
				btnError2.setOnClickListener(new InitEditBox());
			}
			
		}
		
	};
	
	/* 문자 전송 모듈 */
	private void sendSMS(String phoneNumber, String message) throws Exception
    {        
		SmsManager sms = SmsManager.getDefault(); 
        sms.sendTextMessage(phoneNumber, null, message, null, null);  
        
        MUtils.log("FIND_ACCOUNT", "[Send SMS] Phone Number: " + phoneNumber + "| Message: " + message);
    }


	/* 기본 화면으로 초기화하는 클래스 */
	public class InitEditBox implements View.OnClickListener{

		@Override
		public void onClick(View arg0) {
			MUtils.log("FIND_ACCOUNT", "[Cancel] InitEditBox");
			   
			  
			editName.setText("");
			editEmail.setText("");
			editId.setText("");
			editPhone.setText("");
			textResult.setVisibility(View.INVISIBLE);
			btnError.setVisibility(View.INVISIBLE);
			textResult2.setVisibility(View.INVISIBLE);
			btnError2.setVisibility(View.INVISIBLE);
			finish();
			
		}
		
	}
	
	/* 확인 버튼 클릭시, ID 검색 모듈 */
	public class FindIdConfirm implements View.OnClickListener{

		@Override
		public void onClick(View arg0) {
			MUtils.log("FIND_ACCOUNT", "[Find ID] Searching ID from DB sever");
			/* 입력 후, 키보드 숨기기 */
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editName.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(editEmail.getWindowToken(), 0);

			View focusView = null;
			
			editName.setError(null);
			editEmail.setError(null);
			
			if(editName.getText().toString().equals("") ){
				editName.setError(getString(R.string.error_field_required));
				focusView = editName;
				focusView.requestFocus();
			}else if(editEmail.getText().toString().equals("")){
				editEmail.setError(getString(R.string.error_field_required));
				focusView = editEmail;
				focusView.requestFocus();
			}else {
				
				// 서버 DB 검색 
				FindAccountThread mThread = new FindAccountThread(mIdHandler
												, 0
												, editName.getText().toString()
												, editEmail.getText().toString()
												, null
												, null);
				mThread.setDaemon(true);
				mThread.start();
			}
		}
			
	}
	
	/* 전송 버튼 클릭 시, 비밀번호 검색 모듈 */
	public class FindPwdSend implements View.OnClickListener{
		
		@Override
		public void onClick(View arg0) {
			MUtils.log("FIND_ACCOUNT", "[Find Password] Searching password from DB server");
			
			/* 입력 후, 키보드 숨기기 */
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(editId.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(editPhone.getWindowToken(), 0);

			editId.setError(null);
			editPhone.setError(null);
			
			if(editId.getText().toString().equals("") ){
				editId.setError(getString(R.string.error_field_required));
				
			}else if(editPhone.getText().toString().equals("")){
				editPhone.setError(getString(R.string.error_field_required));
				
			}else {
				FindAccountThread mThread = new FindAccountThread(mPwdHandler
												, 1
												, null
												, null
												, editId.getText().toString()
												, editPhone.getText().toString());
				mThread.setDaemon(true);
				mThread.start();
			}
		}
			
	}
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {         
		super.onCreate(savedInstanceState);   
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		MUtils.log("FIND_ACCOUNT", "[onCreate] Start FindAccountActivity");
		
		TabHost tabHost = getTabHost(); 
		LayoutInflater.from(this).inflate(R.layout.activity_find_account, tabHost.getTabContentView(), true);           
		tabHost.addTab(tabHost.newTabSpec("SearchId").setIndicator("아이디 찾기").setContent(R.id.tab_searchId));         
		tabHost.addTab(tabHost.newTabSpec("SearchPwd").setIndicator("비밀번호 찾기").setContent(R.id.tab_searchPwd));        

		textResult = (TextView)findViewById(R.id.resultText);
		textResult2 = (TextView)findViewById(R.id.resultText2);
		
		editName = (EditText)findViewById(R.id.editName);
		editEmail = (EditText)findViewById(R.id.editEmail);
		editId = (EditText)findViewById(R.id.editId);
		editPhone = (EditText)findViewById(R.id.editPhone);
	
		btnConfirm = (Button)findViewById(R.id.btn_confirm);
		btnSend = (Button)findViewById(R.id.btn_send);
		btnCancel = (Button)findViewById(R.id.btn_cancel);
		btnCancel2 = (Button)findViewById(R.id.btn_cancel2);
		btnError = (Button)findViewById(R.id.btn_error);
		btnError2 = (Button)findViewById(R.id.btn_error2);
		
		
		btnConfirm.setOnClickListener(new FindIdConfirm());	// 아이디 찾기 - 확인 버튼 누른 경우 
		btnSend.setOnClickListener(new FindPwdSend()); 		// 비밀번호 찾기 - 전송 버튼 누른 경우 
		btnCancel.setOnClickListener(new InitEditBox()); 	// 아이디 찾기 - 취소 버튼 
		btnCancel2.setOnClickListener(new InitEditBox()); 	// 비밀번호 찾기 - 취소 버튼 
	
	}

	
}
